/*
This script is used to initialize DB.
User need to change variables as below:
    host_port  :  host and port, such as localhost:22222
    db_name    :  db name, such as "test"
    db_owner   :  db user name
    db_passwd  :  db password 
*/
host_port = "localhost:22002"
db_name   = "gate_guard"
db_owner  = "dev"
db_passwd = "Aa123456"


function create_collection_if_no_exist(collection_new) {
    var cols = db.getCollectionNames();
    var i = 0;
    for (; i < cols.length; i++) {
        var tmp = cols[i];
        if (tmp == collection_new) {
            print("warning: already exist " + collection_new);
            return false;
        }
    }
    var rst = db.createCollection(collection_new);
    if (1 != rst.ok) {
        print("error: fail to create " + collection_new + ". " + rst.errmsg);
        print("error: stop to initialize db!");
        quit();
        return false;
    }
    print("info: success to create " + collection_new);
    return true;
}

function create_all_collections() {
    create_collection_if_no_exist("account");

    create_collection_if_no_exist("attendance");
    db.attendance.createIndex({a_mm: -1, u_id: 1}, {name: "update", background: true});

    create_collection_if_no_exist("config");
    create_collection_if_no_exist("face_feature");
    create_collection_if_no_exist("ipc");
    create_collection_if_no_exist("guard");

    create_collection_if_no_exist("record_stranger");
    db.record_stranger.createIndex({r_at: -1}, {name: "r_at_-1", background: true});
    db.record_stranger.createIndex({d_id: 1, r_at: 1, track_id: 1}, {name: "counting", background: true});

    create_collection_if_no_exist("record_user");
    db.record_user.createIndex({r_at: -1}, {name: "r_at_-1", background: true});
    db.record_user.createIndex({u_nm: -1, u_tp: 1, r_at: -1}, {name: "search", background: true});
    db.record_user.createIndex({u_id: 1, r_at: -1}, {name: "attendance", background: true});
    db.record_user.createIndex({d_id: 1, r_at: 1, u_id: 1}, {name: "counting", background: true});

    create_collection_if_no_exist("user");
    db.user.createIndex({u_dm: 1, u_tp: 1, u_no: 1}, {name: "user_sort", background: true});
    db.user.createIndex({u_tp: -1, u_nm: 1}, {name: "guest_sort", background: true});
}

conn = new Mongo(host_port);
db = conn.getDB(db_name);
db.auth(db_owner, db_passwd);
create_all_collections();
print("info: success to build index.")
quit();
